package com.txc.cloud.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.txc.cloud.admin.common.constant.CacheKeyConstant;
import com.txc.cloud.admin.entity.RoleDeptEntity;
import com.txc.cloud.admin.entity.RoleEntity;
import com.txc.cloud.admin.mapper.RoleDeptMapper;
import com.txc.cloud.admin.mapper.RoleMapper;
import com.txc.cloud.admin.service.IDeptService;
import com.txc.cloud.admin.service.IRoleDeptService;
import com.txc.common.config.mybatisplus.constant.DataScopeConstants;
import com.txc.common.global.model.SysRole;
import com.txc.common.global.model.LoginUser;
import com.txc.common.global.model.entity.BaseEntity;
import com.txc.common.utils.format.ObjectFormat;
import com.txc.common.utils.middleware.RedisUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.txc.cloud.admin.common.constant.CacheKeyConstant.*;
import static com.txc.common.global.constant.NumConstant.ZERO;

/**
 * @ClassName: IRoleDeptServiceImpl
 * @Author: TXC
 * @Date: 2023-08-15 15:46
 **/
@Service
public class RoleDeptServiceImpl extends ServiceImpl<RoleDeptMapper, RoleDeptEntity> implements IRoleDeptService {
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private IDeptService deptService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void flush(Long roleId, List<Long> deptIds) {
        List<RoleDeptEntity> roleDeptList =
                baseMapper.selectList(Wrappers.<RoleDeptEntity>lambdaQuery().eq(RoleDeptEntity::getRoleId, roleId));
        Map<Long, RoleDeptEntity> roleDeptMap =
                roleDeptList.stream().collect(Collectors.toMap(RoleDeptEntity::getDeptId, e -> e));
        deptIds.forEach(deptId -> {
            RoleDeptEntity roleDept = roleDeptMap.get(deptId);
            if (ObjectUtil.isNotNull(roleDept)) {
                roleDeptMap.remove(deptId);
            } else {
                RoleDeptEntity roleDeptEntity = new RoleDeptEntity();
                roleDeptEntity.setRoleId(roleId);
                roleDeptEntity.setDeptId(deptId);
                roleDeptEntity.insert();
            }
        });
        roleDeptMap.forEach((k, v) -> v.deleteById());
    }

    @Override
    public List<Long> getDeptIds(Long roleId) {
        Object deptIdCache = redisUtils.get(CacheKeyConstant.generateKey(ADMIN_ROLE_DEPT, roleId));
        List<Long> deptIds;
        if (ObjectUtil.isNotNull(deptIdCache)) {
            deptIds = ObjectFormat.objToObject(deptIdCache, List.class);
        } else {
            RoleEntity role = roleMapper.selectById(roleId);
            if (DataScopeConstants.DATA_SCOPE_CUSTOM.equals(role.getDataScope())) {
                deptIds = baseMapper.selectList(Wrappers.<RoleDeptEntity>lambdaQuery().eq(RoleDeptEntity::getRoleId,
                        roleId)).stream().map(BaseEntity::getId).collect(Collectors.toList());
                redisUtils.set(CacheKeyConstant.generateKey(ADMIN_ROLE_DEPT, roleId), deptIds);
            } else {
                return null;
            }
        }
        return deptIds;
    }

    @Override
    public List<Long> getDeptIds(SysRole role, LoginUser loginUser) {
        if (DataScopeConstants.DATA_SCOPE_CUSTOM.equals(role.getDataScope())) {
            return getDeptIds(role.getId());
        } else if (DataScopeConstants.DATA_SCOPE_DEPT.equals(role.getDataScope())) {
            return Collections.singletonList(loginUser.getDeptId());
        }else if (DataScopeConstants.DATA_SCOPE_DEPT_AND_CHILD.equals(role.getDataScope())) {
            return deptService.getDeptAndChild(loginUser.getDeptId()).get(ZERO).obtainGetSubNode()
                    .stream().map(v -> Long.valueOf(v.toString())).collect(Collectors.toList());
        }else {
            return Collections.emptyList();
        }
    }
}
